import React, {Component,} from 'react'
import {connect,} from 'react-redux'
import AppLayout from "../../layouts/AppLayout";
import './AI.css'
import AIGameCard from "./AIGameCard/AIGameCard";
import {Toast,} from "antd-mobile";
import Huo from "../../res/images/web/AI/huo@2x.png"
import Guo from "../../res/images/web/AI/guo@2x.png"
import {withRouter,} from 'react-router-dom'
import GameAIModel from "../../model/GameAIModel";
import _ from "lodash";
import {GlobalStore} from "../../context";
import DownloadHint from "../../shared-components/DownloadHint/DownloadHint";

class AIContainer extends Component {

    constructor(props) {
        super(props)
        this.state = {
            gameListHandler: null,
            p: 0,
            atTop: true,
            end: false,
            px: 0,
            downloadShow: true,
        }
        // this.gameListHandler = null
    }



    componentDidMount() {
        this.setDownloadShow()
        this.getHots()
        this.getResults()
        this.getVodLiveList()
        // const today = this.props.today
        // this.props.doFetchGameListAll({
        //     date: today,
        // })
        //     .then(() => {
        //         const games = this.props.games
        //         const today = this.props.today
        //         const {
        //             teams,
        //             events,
        //             stages,
        //             matches,
        //         } = games[today]
        //         this.setState({
        //             gameListHandler: new GameListHandler({matches, teams, events, stages,})
        //         })
        //     })
    }

    setDownloadShow = () => {
        const downloadShow = this.context.downloadApp.show
        this.setState({
            downloadShow,
        })
    }

    hidden = () => {
        this.context.downloadApp.hidden()
        this.setState({
            downloadShow: false,
        })
    }

    getVodLiveList = () => {
        this.props.doFetchGameVodLiveList()
    }
    getResults = () => {
        this.props.doGetAIResultList({
            p: this.state.px,
        })
    }

    getHots = () => {
        const p = this.props.game.hotAi.p
        const s = this.props.game.hotAi.s
        const end = this.state.end
        if (end) return
        if (p === 0 && s === 0) {
            this.props.doGetHotAIList()
                .then((res) => {
                    const list = res.data.ok || []
                    if (list.length < 10) {
                        this.setState({
                            end: true,
                        })
                    }
                })
        } else {
            this.props.doGetHotAIList({
                p: p + 1,
                style: s,
            })
                .then((res) => {
                    const list = res.data.ok
                    if (list.length < 10) {
                        this.setState({
                            end: true,
                        })
                    }
                })
        }

    }

    onScroll = _.throttle(() => {

        const ctn = this.scrollCtn
        const top = ctn.scrollTop
        const ScrollHei = ctn.scrollHeight
        const clientHei = ctn.clientHeight
        const gap = ScrollHei - top - clientHei
        if (top > 0) {
            this.setState({
                atTop: false,
            })
            if (gap === 0) {
                this.getHots()
                const end = this.state.end
                if (end) {
                    Toast.info('数据已加载完毕', 1,)
                }
            }
        } else if (top === 0) {
            this.setState({
                atTop: true,
            })
        }
    }, 100)

    goToGame = (e, detail) => {
        const history = this.props.history
        e.stopPropagation()
        history.push(`./game/${detail.matchId}`, {matchId: detail.matchId, status: detail.status, AIBtnClick: true, date:'',})
    }

    onScrollX = _.throttle(() => {
        const ctn = this.scrollXCtn
        const windowWidth = document.documentElement.clientWidth
        const x = ctn.scrollLeft
        const scrollWidth = ctn.scrollWidth
        if (windowWidth + x === scrollWidth) {
            this.setState({
                px: this.state.px + 1,
            }, () => {
                this.getResults()
            })
        }
    }, 100)

    render() {

        let hot = this.props.game.hotAi.list
        let style = 0
        let resultDate = this.props.game.aiResult[style] ? this.props.game.aiResult[style] : {}
        let result = []
        Object.values(resultDate).map(vals => {
            result.push(...vals)
        })

        const resultTemplate = result.map((game, index) => {
            const teamStyle = {
                flex: 1,
                fontSize: '12px',
                fontWeight: 600,
                color: 'rgba(51,51,51,1)',
                lineHeight: '16px',
                textAlign: 'center',
            }
            let model = new GameAIModel(game)
            let RQ = model.RQ()
            let DXQ = model.DXQ()
            let SFP = model.SFP()

            let resultMapper = {
                1: '准',
                2: '错',
                3: '走',
            }

            let bgMapper = {
                1: '#FA7268',
                3: '#FFA500',
                2: '#BEBEBE',
            }


            let odd = null
            let RQOdd = <div
                className='AI-result-odd'
                style={{
                    backgroundColor: bgMapper[RQ.result],
                }}
            >
                <span>
                    {`${RQ.title}-${RQ.subTitle}：${RQ.resultRate}%`}
                </span>
                <span>
                    {resultMapper[RQ.result]}
                </span>
            </div>

            let SFPOdd = <div
                className='AI-result-odd'
                style={{
                    backgroundColor: bgMapper[SFP.result],
                }}
            >
                <span>
                    {`首选：${SFP.first}% 次选：${SFP.second}%`}
                    {/*{`${SFPTitle}：首选-${largest}% 次选--${middle}%`}*/}
                </span>
                <span>
                    {resultMapper[SFP.result]}
                </span>
            </div>

            let DXQOdd = <div
                className='AI-result-odd'
                style={{
                    backgroundColor: bgMapper[DXQ.result],
                }}
            >
                <span>
                    {`${DXQ.title}-${DXQ.subTitle}：${DXQ.resultRate}%`}
                </span>
                <span>
                    {resultMapper[DXQ.result]}
                </span>
            </div>

            // 近期预测：胜选规则，优先显示（1、让球  2、胜平负 3、大小球）依次显示
            if (RQ.result !== 2) {
                odd = RQOdd
            } else if (SFP.result !== 2) {
                odd = SFPOdd
            } else {
                odd = DXQOdd
            }

            // let x = (index + 1) % 3
            // if (x === 1) {
            //     odd = RQOdd
            //     if (RQ.result === 2) {
            //         odd = SFP.result === 1 || SFP.result === 3 ? SFPOdd : DXQOdd
            //     }
            // } else if (x === 2) {
            //     odd = SFPOdd
            //     if (SFP.result === 2) {
            //         odd = DXQ.result === 1 || DXQ.result === 3 ? DXQOdd : RQOdd
            //     }
            // } else if (x === 0) {
            //     odd = DXQOdd
            //     if (DXQ.result === 2) {
            //         odd = RQ.result === 1 || RQ.result === 3 ? RQOdd : SFPOdd
            //     }
            // }

            const detail = model.detail()

            return <div
                key={index}
                className='AI-result-ctn'
                // onClick={() => this.props.history.push(`../game/${detail.matchId}`)}
                onClick={(e) => this.goToGame(e, detail)}
            >

                <div
                    className='flex-space-between-align-center'
                    style={{padding: '8px'}}
                >
                        <span style={{
                            fontSize: '12px',
                            lineHeight: '17px',
                            color: 'rgba(51, 51, 51, 0.4)'
                        }}>
                            {detail.c}
                        </span>
                    <span style={{
                        fontSize: '12px',
                        lineHeight: '17px',
                    }}>
                        {/*{detail.time}*/}
                        {detail.isToday ? '今天 ' + detail.time : detail.date + ' ' + detail.time}
                    </span>
                </div>

                <div className='flex-center-align-center' style={{
                    position: 'absolute',
                    top: '50%',
                    left: '50%',
                    transform: 'translate(-50%, -50%)',
                    width: '100%',
                }}>
                    <span style={teamStyle}>{detail.host.name}</span>
                    <span> vs </span>
                    <span style={teamStyle}>{detail.away.name}</span>
                </div>

                {odd}

            </div>
        })
        const hotTemplate = hot.map((game, index) => <AIGameCard game={game} key={index}/>)
        // let listTemplate = null
        // const handler = this.state.gameListHandler
        //
        // if (handler !== null) {
        //     const schedule = handler.listSchedule()
        //     const live = handler.listLive()
        //     const cancel = handler.listCancel()
        //
        //     let gameList = [...live, ...schedule]
        //     if (gameList.length === 0) {
        //         gameList = [...cancel]
        //     }
        //
        //     listTemplate = gameList.map(game => <AIGameCard game={game} key={game.matchId}/>)
        // }


        const atTop = this.state.atTop
        const resultCtnHeight = atTop ? '112px' : '0px'

        const moreResult = <div
            onClick={() => this.props.history.push('../recent-ai')}
        >
            <span
                className='gray-text'
                style={{lineHeight: '40px',}}
            >查看更多</span>
        </div>

        let resultFirst
        const firstResult = result[0]
        if (firstResult) {
            const firstModal = new GameAIModel(firstResult)
            const firstDetail = firstModal.detail()
            const matchId = firstDetail.matchId

            resultFirst = <div
                className='flex-space-between-align-center'
                style={{width: '70%',}}
                onClick={() => this.props.history.push('../game/' + matchId)}
            >
                <div
                    style={{
                        width: '60%',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                    }}
                >
                    <span
                        style={{
                            // width: '100%',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                        }}
                    >{firstDetail.host.name} vs {firstDetail.away.name}</span>
                </div>

                <div
                    className='flex-space-between-align-center'
                    style={{
                        width: '67px',
                        height: '24px',
                        background: 'rgba(250,114,104,1)',
                        borderRadius: '1px',
                        color: '#fff',
                        padding: '4px',
                    }}
                >
                    <span>分析</span>
                    <span>准</span>
                </div>

            </div>

        }
        const download = this.state.downloadShow

        const normalCtnCls = atTop
            ? 'hot-ai-list-ctn'
            : 'hot-ai-list-ctn hot-ai-list-ctn-unfolded'
        const downloadShowCls = atTop
            ? 'hot-ai-list-ctn-d'
            : 'hot-ai-list-ctn hot-ai-list-ctn-unfolded-d'


        return <AppLayout>
            {download ? <DownloadHint onHidden={this.hidden}/> : null}
            <div
                className='ai-ctn'
                // onScroll={e => this.onScroll(e)}
            >
                <div className='ai-ctn-head'>
                    <p>小应分析</p>
                    <span
                        onClick={() => this.props.history.push('../my-ai')}
                    >我购买的</span>
                </div>


                <div
                    className='flex-space-between-align-center'
                    style={{
                        padding: '12px',
                        height: '40px',
                    }}
                >
                    <div
                        className='flex-align-center'
                        style={{width: '30%',}}
                    >
                        <img src={Guo} style={{width: 16, height: 16, marginRight: '4px',}} alt=''/>
                        <p>近期分析</p>
                    </div>

                    {atTop
                        ? moreResult
                        : resultFirst
                    }
                </div>

                <div
                    className={`AI-result-list-ctn${atTop ? '' : ' AI-result-list-ctn-folded'}`}
                    onScroll={this.onScrollX}
                    ref={el => this.scrollXCtn = el}
                >
                    {resultTemplate}
                </div>


                <div
                    className='ai-ctn-main'
                >
                    <div className='flex-align-center' style={{
                        paddingTop: 16,
                        paddingBottom: 12,
                    }}>
                        <img src={Huo} style={{width: 16, height: 16, marginRight: '4px',}} alt=''/>
                        <p>热门分析</p>
                    </div>

                    <div
                        // onScroll={_.throttle(this.onScroll, 100)}
                        onScroll={this.onScroll}
                        ref={el => this.scrollCtn = el}
                        className={download
                            ? downloadShowCls
                            : normalCtnCls
                        }
                        // style={{
                        //     // height: 'auto',
                        //     height: `calc(100vh - 64px - 40px - 50px - ${resultCtnHeight} - 44px)`,
                        //     overflowY: 'scroll',
                        // }}
                    >
                        {hotTemplate}
                        <div style={{textAlign: 'center', marginTop: '24px',}}>
                            <span className='gray-text'>下滑加载更多～</span>
                        </div>
                    </div>
                    {/*{listTemplate}*/}
                    {/*<WingBlank>*/}
                    {/*    <div className='ai-plans-ctn flex-space-between-align-center'>*/}
                    {/*        /!*{AIPlan(PlanAIcon, 'A')}*!/*/}
                    {/*        /!*{AIPlan(PlanBIcon, 'B')}*!/*/}
                    {/*        /!*<AIPlan type='A'/>*!/*/}
                    {/*        /!*<AIPlan type='B'/>*!/*/}
                    {/*    </div>*/}
                    {/*</WingBlank>*/}
                </div>

            </div>
        </AppLayout>
    }
}

AIContainer.contextType = GlobalStore

const mapState = state => ({
    game: state.game,
    games: state.game.games,
    today: state.game.today,
})

const mapDispatch = dispatch => ({
    doFetchGameList: (payload) => dispatch.game.doFetchGameList(payload),
    doFetchGameListAll: (payload) => dispatch.game.doFetchGameListAll(payload),
    doFetchGameListLive: (payload) => dispatch.game.doFetchGameListLive(payload),
    doGetAIResultList: (payload) => dispatch.game.doGetAIResultList(payload),
    doGetHotAIList: (payload) => dispatch.game.doGetHotAIList(payload),
    doFetchGameVodLiveList: () => dispatch.game.doFetchGameVodLiveList()
})

export default connect(mapState, mapDispatch)(withRouter(AIContainer))
